package demo.deep;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.xml.crypto.Data;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

@RestController
@RequestMapping("sse")
public class SseApi {
    /**
     * 流式编程 SSE协议
     * 基于http/https协议 兼容性好
     * 单向通信机制
     * SSE支持服务端向客户端消息的单向推送，在建立连接后，服务端可以持续的向客户端发送数据，而客户端不能通过同一个连接向服务器发送响应
     * 自动重连 连接中断之后，浏览器会尝试重新连接
     * 自定义数据格式 在请求头中使用 “text/even-stream” 标记为一个流式事件，可以持续获取到服务器信息
     */
    @RequestMapping("data")
    public void data(HttpServletResponse response) throws IOException, InterruptedException {
        response.setContentType("text/event-stream;charset=utf-8");

        PrintWriter writer = response.getWriter();

        for (int i = 0; i < 10; i++) {
            String s = "data: " + new Date() + "\n\n";
            writer.write(s);

            writer.flush();

            Thread.sleep(1000);
        }
    }

    @RequestMapping("retry")
    public void retry(HttpServletResponse response) throws IOException, InterruptedException {
        System.out.println("收到retry");

        response.setContentType("text/event-stream;charset=utf-8");

        PrintWriter writer = response.getWriter();

        String s = "retry: 1000\n";
        s += "data: " + new Date() + "\n\n";

        writer.write(s);

        writer.flush();
    }

    @RequestMapping("event")
    public void even(HttpServletResponse response) throws IOException, InterruptedException {
        response.setContentType("text/event-stream;charset=utf-8");
        PrintWriter writer = response.getWriter();

        for (int i = 0; i < 20; i++) {
//            String msg = "event: foo\n";
            String msg = "";
            msg += "data: " + new Date() + "\n\n";
            writer.write(msg);
            writer.flush();
            if (i == 10) {
                String s = "event: end\n";
                s += "data: " + new Date() + "event 结束" + "\n\n";
                writer.write(s);
                writer.flush();
            }
            Thread.sleep(1000);
        }

    }
}
